<template>
  <div :class="['avatar-list', `avatar-list-${size}`]">
    <ul>
      <component :is="renderItems" />
      <template v-if="totalSize > maxLength">
        <avatar-list-item>{{ `+${totalSize - maxLength}` }}</avatar-list-item>
      </template>
    </ul>
  </div>
</template>
<script lang="ts">
export interface AvatarItemInjectData {
  size: ComputedRef<AvatarSize>;
}

export const avatarListKey: InjectionKey<AvatarItemInjectData> = Symbol();
</script>
<script setup lang="ts">
import type { InjectionKey, ComputedRef, PropType } from 'vue';
import { provide, ref, computed, onMounted, useSlots, onUpdated } from 'vue';
import { filterEmpty } from '@/utils/vnode-util';
import AvatarListItem from './item.vue';
import type { AvatarSize } from 'ant-design-vue/es/avatar';

const props = defineProps({
  size: {
    type: String as PropType<AvatarSize>,
    default: 'default' as AvatarSize,
  },
  maxLength: {
    type: Number,
    default: 5,
  },
});
defineSlots<{
  default: () => any;
}>();
const totalSize = ref(0);
const slots = useSlots();
const renderItems = computed(() => () => filterEmpty(slots.default?.()).slice(0, props.maxLength));
onMounted(() => {
  totalSize.value = filterEmpty(slots.default?.()).length;
});
onUpdated(() => {
  totalSize.value = filterEmpty(slots.default?.()).length;
});
provide(avatarListKey, {
  size: computed(() => props.size),
});
</script>

<style lang="less" scoped>
.avatar-list {
  display: inline-block;

  ul {
    display: inline-block;
    margin-left: 8px;
    font-size: 0;
  }
}
</style>
